<template>
	<div class="home-box">
		<el-form v-show="showSearch" :inline="true" :model="employeeSearchForm">
			<el-form-item label="用户工号">
				<el-input v-model="employeeSearchForm.u.userNumber" placeholder="用户工号" clearable />
			</el-form-item>
			<el-form-item label="员工姓名">
				<el-input v-model="employeeSearchForm.u.userName" placeholder="用户姓名" clearable />
			</el-form-item>
			<el-form-item label="分组名称">
				<el-select v-model="employeeSearchForm.u.groupOfEmployee_name" placeholder="请选择分组" clearable filterable :options="groupOptions">
					<el-option
						v-for="item in groupOptions"
						:key="item.value"
						:label="item.label"
						:value="item.value"
					/>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="getEmployeeData">查询</el-button>
			</el-form-item>
		</el-form>
		<el-card>
			<el-table
				v-loading="employeeLoading"
				:data="employeeTableData"
				element-loading-text="加载中..."
				border
				@row-dblclick="openAddDialog"
			>
				<el-table-column prop="用户ID" label="用户ID" width="120" />
				<el-table-column prop="用户ID" label="员工ID" width="120" />
				<el-table-column prop="员工状态" label="员工状态" width="100" />
				<el-table-column prop="员工工号" label="员工工号" width="100" />
				<el-table-column prop="员工姓名" label="员工姓名" width="120" />
				<el-table-column prop="员工分组ID" label="分组ID" width="120" />
				<el-table-column prop="员工分组编码" label="分组编码" width="100" />
				<el-table-column prop="员工分组名称" label="分组名称" width="120" />
				<el-table-column label="操作" width="180">
					<template #default="{ row }">
						<el-button type="primary" size="small" @click="openAddDialog(row)">查看用户</el-button>
						<el-button type="primary" size="small" @click="openUpdatePwdDialog(row)">修改密码</el-button>
						<el-button type="danger" size="small" @click="handleDeleteUser(row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<pagination
				v-show="employeeTotal > 0"
				v-model:page="employeeSearchForm.p.page_number"
				v-model:limit="employeeSearchForm.p.page_size"
				:total="employeeTotal"
				@pagination="getEmployeeData"
			/>
		</el-card>

		<distribute-permission
			v-model="distributePermissionVisible"
			:role-id="selectRoleId"
		>
		</distribute-permission>

		<!-- 新增员工弹窗 -->
		<el-dialog title="新增员工" v-model="addDialogVisible" width="400px">
			<el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="90px">
				<el-form-item label="员工编号">
					<el-input v-model="addForm.employeeCode" disabled />
				</el-form-item>
				<el-form-item label="员工姓名">
					<el-input v-model="addForm.employeeName" disabled />
				</el-form-item>
				<el-form-item label="分组编号">
					<el-input v-model="addForm.groupNumber" disabled />
				</el-form-item>
				<el-form-item label="所属部门">
					<el-input v-model="addForm.department" placeholder="请选择所属部门" readonly>
						<template #append>
							<el-button icon="el-icon-search" @click="departmentDialogVisible = true"></el-button>
						</template>
					</el-input>
				</el-form-item>
				<el-form-item label="密码" prop="passWord">
					<el-input v-model="addForm.passWord" type="password" autocomplete="off" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="addDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitAddEmployee">确定</el-button>
			</template>
		</el-dialog>

		<!-- 部门选择弹窗 -->
		<el-dialog title="选择所属部门" v-model="departmentDialogVisible" width="500px">
			<el-input v-model="departmentSearch" placeholder="请输入部门名称搜索" @input="getDepartmentList" style="margin-bottom: 10px;" />
			<el-table :data="departmentList" v-loading="departmentLoading" @row-dblclick="handleSelectDepartment">
				<el-table-column prop="部门名称" label="部门名称" />
				<el-table-column prop="所属部门" label="所属部门" />
			</el-table>
			<template #footer>
				<el-button @click="departmentDialogVisible = false">取消</el-button>
			</template>
		</el-dialog>

		<div style="margin-top: 20px; text-align: right;">
			<el-button type="primary" @click="onCreateUser">创建用户</el-button>
			<el-button @click="onQueryUser">员工查询</el-button>
		</div>
		<el-card>
			<el-table
				v-loading="archiveLoading"
				:data="archiveTableData"
				element-loading-text="加载中..."
				border
			>
				<el-table-column prop="主键ID" label="ID" width="80" />
				<el-table-column prop="员工工号" label="工号" width="100" />
				<el-table-column prop="员工编号" label="编号" width="100" />
				<el-table-column prop="员工姓名" label="姓名" width="120" />
				<el-table-column prop="在职状态" label="在职状态" width="100" />
				<el-table-column prop="禁用状态" label="禁用状态" width="100" />
				<el-table-column prop="入职日期" label="入职日期" width="120" />
				<el-table-column prop="婚姻状态" label="婚姻" width="80" />
				<el-table-column prop="身份证" label="身份证" width="150" />
				<el-table-column prop="联系地址" label="联系地址" width="180" />
				<el-table-column prop="移动电话" label="电话" width="120" />
				<el-table-column prop="电子邮箱" label="邮箱" width="150" />
				<el-table-column label="操作" width="100">
					<template #default="{ row }">
						<el-button
							v-if="!archiveSearchForm.e || !archiveSearchForm.e.where"
							type="primary"
							size="small"
							@click="openAddDialog(row)"
						>新增用户</el-button>
						<el-button
							v-else
							type="info"
							size="small"
							@click="openViewDialog(row)"
						>查看员工档案</el-button>
					</template>
				</el-table-column>
			</el-table>
			<pagination
				v-show="archiveTotal > 0"
				v-model:page="archiveSearchForm.p.page_number"
				v-model:limit="archiveSearchForm.p.page_size"
				:total="archiveTotal"
				@pagination="getArchiveData"
			/>
		</el-card>
		<el-dialog title="新增用户登录账号" v-model="addDialogVisible" width="400px">
			<el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="90px">
				<el-form-item label="员工编号">
					<el-input v-model="addForm.employeeCode" disabled />
				</el-form-item>
				<el-form-item label="员工姓名">
					<el-input v-model="addForm.employeeName" disabled />
				</el-form-item>
				<el-form-item label="分组编号" prop="groupNumber">
					<el-select v-model="addForm.groupNumber" placeholder="请选择分组" filterable clearable>
						<el-option v-for="item in groupOptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="密码" prop="passWord">
					<el-input v-model="addForm.passWord" type="password" autocomplete="off" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="addDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitAddEmployee">确定</el-button>
			</template>
		</el-dialog>

		<!-- 查看员工档案弹窗 -->
		<el-dialog title="员工档案" v-model="viewDialogVisible" width="600px">
			<el-form :model="viewRow" label-width="90px">
				<el-form-item label="员工工号">
					<el-input v-model="viewRow.员工工号" disabled />
				</el-form-item>
				<el-form-item label="员工姓名">
					<el-input v-model="viewRow.员工姓名" disabled />
				</el-form-item>
				<el-form-item label="分组名称">
					<el-input v-model="viewRow.员工分组名称" disabled />
				</el-form-item>
				<el-form-item label="在职状态">
					<el-input v-model="viewRow.在职状态" disabled />
				</el-form-item>
				<el-form-item label="禁用状态">
					<el-input v-model="viewRow.禁用状态" disabled />
				</el-form-item>
				<el-form-item label="入职日期">
					<el-input v-model="viewRow.入职日期" disabled />
				</el-form-item>
				<el-form-item label="婚姻状态">
					<el-input v-model="viewRow.婚姻状态" disabled />
				</el-form-item>
				<el-form-item label="身份证">
					<el-input v-model="viewRow.身份证" disabled />
				</el-form-item>
				<el-form-item label="联系地址">
					<el-input v-model="viewRow.联系地址" disabled />
				</el-form-item>
				<el-form-item label="移动电话">
					<el-input v-model="viewRow.移动电话" disabled />
				</el-form-item>
				<el-form-item label="电子邮箱">
					<el-input v-model="viewRow.电子邮箱" disabled />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="viewDialogVisible = false">关闭</el-button>
			</template>
		</el-dialog>

		<!-- 修改密码弹窗 -->
		<el-dialog title="修改密码" v-model="updatePwdDialogVisible" width="400px">
			<el-form :model="updatePwdForm" :rules="updatePwdFormRules" ref="updatePwdFormRef" label-width="90px">
				<el-form-item label="员工工号">
					<el-input v-model="updatePwdForm.username" disabled />
				</el-form-item>
				<el-form-item label="原密码" prop="password">
					<el-input v-model="updatePwdForm.password" type="password" autocomplete="off" />
				</el-form-item>
				<el-form-item label="新密码" prop="new_password">
					<el-input v-model="updatePwdForm.new_password" type="password" autocomplete="off" />
				</el-form-item>
				<el-form-item label="再次输入" prop="confirm_new_password">
					<el-input v-model="updatePwdForm.confirm_new_password" type="password" autocomplete="off" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="updatePwdDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitUpdatePassword">确定</el-button>
			</template>
		</el-dialog>

		<!-- 部门选择弹窗 -->
		<el-dialog title="选择部门" v-model="departmentDialogVisible" width="600px">
			<el-input v-model="departmentSearch" placeholder="搜索部门" clearable @input="getDepartmentList" />
			<el-table
				v-loading="departmentLoading"
				:data="departmentList"
				element-loading-text="加载中..."
				border
			>
				<el-table-column prop="部门编号" label="部门编号" width="120" />
				<el-table-column prop="部门名称" label="部门名称" width="120" />
				<el-table-column label="操作" width="100">
					<template #default="{ row }">
						<el-button
							type="primary"
							size="small"
							@click="handleSelectDepartment(row)"
						>选择</el-button>
					</template>
				</el-table-column>
			</el-table>
			<template #footer>
				<el-button @click="departmentDialogVisible = false">关闭</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<style lang="scss" scoped>
.home-box {
  .header {
    margin-bottom: 22px;
    text-align: right;
  }
  ::v-deep .el-tag {
    margin-right: 6px;
  }
  .pagination {
    display: flex;
    justify-content: end;
    margin-top: 20px;
  }

}
</style>

<script setup>
import DistributePermission from "./components/distributePermission.vue";
import { localRoleList } from "@/constant/local-role-list";

import { ref, onMounted } from "vue";
import { getEmployeeList, getEmployeeGroupList, addEmployee, employeeArchiveQuery, updatePassword, deleteUserApi, getDepartmentList as getDepartmentListApi } from "@/api/api";
import { ElMessage, ElMessageBox } from "element-plus";

const showSearch = ref(true);

// 数据源
const searchForm = ref({
	id: 0,
	name: "",
	date: "",
	page: 1,
	page_size: 10
});

const tableData = ref([]);
const total = ref(0);
const loading = ref(false);
/**
 * 获取角色列表
 */
const allRoleList = ref([]);
// 获取所有角色数据的方法
const getListData = async() => {
	// const data = await getRoleList();
	// allRoleList.value = data.objs;
	allRoleList.value = localRoleList;
	// await getUserRoles(); // 已注释掉，避免404
};

/**
 * 分配权限
 */
const distributePermissionVisible = ref(false);
const selectRoleId = ref("");
const handleEdit = row => {
	selectRoleId.value = row.id;
	distributePermissionVisible.value = true;
};

const searchEvent = () => {
	searchForm.value.page = 1;
	getListData();
};
const onDownTemplate = () => {
	ElMessage.error("演示模式");
};

// 新增员工档案数据源
const employeeSearchForm = ref({
  u: {
    userNumber: "",
    userName: "",
    groupOfEmployee_name: ""
  },
  p: {
    page_number: 1,
    page_size: 100
  }
});
const employeeTableData = ref([]);
const employeeTotal = ref(0);
const employeeLoading = ref(false);

const getEmployeeData = async () => {
  employeeLoading.value = true;
  await getEmployeeList(employeeSearchForm.value)
    .then(res => {
      console.log('[getEmployeeList 返回]', res); // 新增调试输出
      // 兼容接口返回不是数组的情况
      employeeTableData.value = Array.isArray(res.data.data
) ? res.data.data
 : [];
      employeeTotal.value = res.rows || 0;
      employeeLoading.value = false;
    })
    .catch(() => {
      employeeTableData.value = [];
      employeeLoading.value = false;
    });
};

// 新员工档案数据源
const archiveSearchForm = ref({
  p: {
    page_number: 1,
    page_size: 10
  },
  e: {
    where: false,
    fid: ''
  }
});
const archiveTableData = ref([]);
const archiveTotal = ref(0);
const archiveLoading = ref(false);

const getArchiveData = async () => {
  archiveLoading.value = true;
  await employeeArchiveQuery(archiveSearchForm.value)
    .then(res => {
      console.log('[employeeArchiveQuery 返回]', res);
      // 修正：后端返回结构为 res.data.data
      const arr = Array.isArray(res.data?.data) ? res.data.data : [];
      archiveTableData.value = arr;
      archiveTotal.value = res.data?.rows || 0;
      archiveLoading.value = false;
      console.log('[员工档案表格渲染数据]', archiveTableData.value);
    })
    .catch(() => {
      archiveTableData.value = [];
      archiveLoading.value = false;
    });
};

// 新增员工分组下拉数据源
defineProps([]);
const groupOptions = ref([]);

const getGroupOptions = async () => {
  await getEmployeeGroupList({ page_number: 1, page_size: 100 })
    .then(res => {
      // 修正：后端返回结构为 res.data.data
      const arr = Array.isArray(res.data?.data) ? res.data.data : [];
      groupOptions.value = arr.map(item => ({
        label: item["用户分组名称"],
        value: item["用户分组编码"]
      }));
    });
};

onMounted(() => {
  getListData();
  getGroupOptions();
  getEmployeeData(); // 页面进入时自动查询员工列表
  getArchiveData();  // 页面进入时自动查询员工档案（调用 employeeArchiveQuery）
});

// 新增员工弹窗相关
const addDialogVisible = ref(false);
const addForm = ref({
  employeeCode: '',
  employeeName: '',
  groupNumber: '',
  passWord: '',
  department: ''
});
const addFormRef = ref();
const addFormRules = {
  passWord: [{ required: true, message: '请输入密码', trigger: 'blur' }]
};
const addDialogLoading = ref(false);

function openAddDialog(row) {
  addForm.value.employeeCode = row && row['员工编号'] ? row['员工编号'] : '';
  addForm.value.employeeName = row && row['员工姓名'] ? row['员工姓名'] : '';
  addForm.value.groupNumber = groupOptions.value.length > 0 ? groupOptions.value[0].value : '';
  addForm.value.passWord = '';
  addForm.value.department = row && row['所属部门'] ? row['所属部门'] : '';
  addDialogVisible.value = true;
}

async function submitAddEmployee() {
  if (addDialogLoading.value) return;
  await addFormRef.value.validate(async (valid) => {
    if (!valid) return;
    addDialogLoading.value = true;
    try {
      const params = {
        employeeCode: addForm.value.employeeCode,
        employeeName: addForm.value.employeeName,
        groupNumber: addForm.value.groupNumber,
        passWord: addForm.value.passWord
      };
      const res = await addEmployee(params);
      // 修正：兼容后端结构，判断 res.data?.Result?.ResponseStatus?.IsSuccess
      const isSuccess = res.data?.Result?.ResponseStatus?.IsSuccess === true;
	  console.log('[新增员工返回]', res);
      if (res.data.code == 200) {
        ElMessage.success('新增成功');
        addDialogVisible.value = false;
        addFormRef.value.resetFields();
        getArchiveData();
      } else {
        // 优先展示后端错误信息
        const errMsg = res.data?.Result?.ResponseStatus?.Errors?.[0]?.Message || '新增失败';
        ElMessage.error(errMsg);
      }
    } catch (e) {
      ElMessage.error('请求失败');
    } finally {
      addDialogLoading.value = false;
    }
  });
}

// "创建用户"按钮点击事件
function onCreateUser() {
  archiveSearchForm.value.p.page_number = 1;
  archiveSearchForm.value.p.page_size = 100;
  archiveSearchForm.value.e = { where: false, fid: '' };
  getArchiveData();
}

// "员工查询"按钮点击事件
function onQueryUser() {
  archiveSearchForm.value.p.page_number = 1;
  archiveSearchForm.value.p.page_size = 100;
  archiveSearchForm.value.e = { where: true, fid: '' };
  getArchiveData();
}

// 查看员工档案弹窗逻辑（可根据实际需求完善）
const viewDialogVisible = ref(false);
const viewRow = ref({});
function openViewDialog(row) {
  viewRow.value = row;
  viewDialogVisible.value = true;
}

// 修改密码弹窗相关
const updatePwdDialogVisible = ref(false);
const updatePwdForm = ref({
  username: '',
  password: '',
  new_password: '',
  confirm_new_password: '' // 新增字段
});
const updatePwdFormRef = ref();
const updatePwdFormRules = {
  password: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  new_password: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  confirm_new_password: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== updatePwdForm.value.new_password) {
          callback(new Error('两次输入的新密码不一致'));
        } else {
          callback();
        }
      }, trigger: 'blur' }
  ]
};
const updatePwdLoading = ref(false);
let currentUserRow = null;

function openUpdatePwdDialog(row) {
  currentUserRow = row;
  updatePwdForm.value.username = row['用户工号'] || row['员工工号'] || '';
  updatePwdForm.value.password = '';
  updatePwdForm.value.new_password = '';
  updatePwdForm.value.confirm_new_password = '';
  updatePwdDialogVisible.value = true;
}

async function submitUpdatePassword() {
  if (updatePwdLoading.value) return;
  await updatePwdFormRef.value.validate(async (valid) => {
    if (!valid) return;
    updatePwdLoading.value = true;
    try {
      const params = {
        username: updatePwdForm.value.username,
        password: updatePwdForm.value.password,
        new_password: updatePwdForm.value.new_password
      };
      const res = await updatePassword(params);
      if (res.code === 200) {
        ElMessage.success('密码修改成功');
        updatePwdDialogVisible.value = false;
        updatePwdFormRef.value.resetFields();
      } else {
        ElMessage.error(res.msg || '修改失败');
      }
    } catch (e) {
      ElMessage.error('请求失败');
    } finally {
      updatePwdLoading.value = false;
    }
  });
}

// 删除用户方法
async function handleDeleteUser(row) {
  const userCode = row['用户工号'] || row['员工工号'] || row['employeeCode'] || row['userNumber'];
  const userName = row['员工姓名'] || row['userName'] || '';
  if (!userCode) {
    ElMessage.error('未获取到用户工号，无法删除');
    return;
  }
  try {
    await ElMessageBox.confirm(
      `确定要删除员工【${userName}】（工号：${userCode}）吗？`,
      '提示',
      { type: 'warning' }
    );
    const res = await deleteUserApi({ number: [userCode] });
    if (res.data.code === 200) {
      ElMessage.success('删除成功');
      getEmployeeData();
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (e) {
    // 用户取消或请求异常
  }
}

// 部门选择弹窗相关
const departmentDialogVisible = ref(false);
const departmentList = ref([]);
const departmentLoading = ref(false);
const departmentSearch = ref("");

// 请求部门接口
const getDepartmentList = async () => {
  departmentLoading.value = true;
  await getDepartmentListApi({ keyword: departmentSearch.value })
    .then(res => {
      // 兼容后端结构
      departmentList.value = Array.isArray(res.data?.data) ? res.data.data : [];
      departmentLoading.value = false;
    })
    .catch(() => {
      departmentList.value = [];
      departmentLoading.value = false;
    });
};

// 选择部门回填
function handleSelectDepartment(row) {
  addForm.value.department = row["所属部门"] || row["部门名称"] || row["name"] || "";
  addDialogVisible.value = true;
  departmentDialogVisible.value = false;
}
</script>
<script>
export default {
	name: "get-role-list"
};
</script>